import React, { createContext, useContext, useReducer, useEffect, ReactNode } from 'react';
import { UserInfo, authApi } from '../services/api';

// 认证状态接口
interface AuthState {
  isAuthenticated: boolean;
  user: UserInfo | null;
  loading: boolean;
  error: string | null;
}

// 认证动作类型
type AuthAction =
  | { type: 'LOGIN_START' }
  | { type: 'LOGIN_SUCCESS'; payload: UserInfo }
  | { type: 'LOGIN_FAILURE'; payload: string }
  | { type: 'LOGOUT' }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'CLEAR_ERROR' };

// 初始状态
const initialState: AuthState = {
  isAuthenticated: false,
  user: null,
  loading: true,
  error: null,
};

// 状态管理器
const authReducer = (state: AuthState, action: AuthAction): AuthState => {
  switch (action.type) {
    case 'LOGIN_START':
      return { ...state, loading: true, error: null };
    case 'LOGIN_SUCCESS':
      return {
        ...state,
        isAuthenticated: true,
        user: action.payload,
        loading: false,
        error: null,
      };
    case 'LOGIN_FAILURE':
      return {
        ...state,
        isAuthenticated: false,
        user: null,
        loading: false,
        error: action.payload,
      };
    case 'LOGOUT':
      return {
        ...state,
        isAuthenticated: false,
        user: null,
        loading: false,
        error: null,
      };
    case 'SET_LOADING':
      return { ...state, loading: action.payload };
    case 'CLEAR_ERROR':
      return { ...state, error: null };
    default:
      return state;
  }
};

// 认证上下文接口
interface AuthContextType extends AuthState {
  login: (username: string, password: string, rememberMe?: boolean) => Promise<void>;
  register: (username: string, password: string, confirmPassword: string, 
            nickname?: string, email?: string, phone?: string) => Promise<void>;
  logout: () => Promise<void>;
  clearError: () => void;
}

// 创建认证上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// 认证提供者组件属性
interface AuthProviderProps {
  children: ReactNode;
}

// 认证提供者组件
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [state, dispatch] = useReducer(authReducer, initialState);

  // 组件挂载时检查用户登录状态
  useEffect(() => {
    const checkAuthStatus = async () => {
      const token = localStorage.getItem('token');
      if (token) {
        try {
          const response = await authApi.getCurrentUser();
          if (response.code === 200) {
            dispatch({ type: 'LOGIN_SUCCESS', payload: response.data });
          } else {
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            dispatch({ type: 'LOGOUT' });
          }
        } catch (error) {
          localStorage.removeItem('token');
          localStorage.removeItem('userInfo');
          dispatch({ type: 'LOGOUT' });
        }
      } else {
        dispatch({ type: 'SET_LOADING', payload: false });
      }
    };

    checkAuthStatus();
  }, []);

  // 登录方法
  const login = async (username: string, password: string, rememberMe: boolean = false) => {
    dispatch({ type: 'LOGIN_START' });
    try {
      const response = await authApi.login({ username, password, rememberMe });
      if (response.code === 200) {
        const { token, ...userInfo } = response.data;
        localStorage.setItem('token', token);
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        dispatch({ type: 'LOGIN_SUCCESS', payload: response.data });
      } else {
        dispatch({ type: 'LOGIN_FAILURE', payload: response.message });
      }
    } catch (error: any) {
      const errorMessage = error.response?.data?.message || '登录失败，请稍后重试';
      dispatch({ type: 'LOGIN_FAILURE', payload: errorMessage });
    }
  };

  // 注册方法
  const register = async (
    username: string,
    password: string,
    confirmPassword: string,
    nickname?: string,
    email?: string,
    phone?: string
  ) => {
    dispatch({ type: 'LOGIN_START' });
    try {
      const response = await authApi.register({
        username,
        password,
        confirmPassword,
        nickname,
        email,
        phone,
      });
      if (response.code === 200) {
        // 注册成功后自动登录
        await login(username, password);
      } else {
        dispatch({ type: 'LOGIN_FAILURE', payload: response.message });
      }
    } catch (error: any) {
      const errorMessage = error.response?.data?.message || '注册失败，请稍后重试';
      dispatch({ type: 'LOGIN_FAILURE', payload: errorMessage });
    }
  };

  // 登出方法
  const logout = async () => {
    try {
      await authApi.logout();
    } catch (error) {
      console.error('登出请求失败:', error);
    } finally {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      dispatch({ type: 'LOGOUT' });
    }
  };

  // 清除错误
  const clearError = () => {
    dispatch({ type: 'CLEAR_ERROR' });
  };

  const value: AuthContextType = {
    ...state,
    login,
    register,
    logout,
    clearError,
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

// 使用认证上下文的钩子
export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth必须在AuthProvider内部使用');
  }
  return context;
};